package com.engine.cn.factory;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class DeviceServiceFactory {
    // Spring会自动注入所有DeviceService实现，这是除了@Autoview之外的其他注入方法
    private final Map<String, DeviceService> deviceServiceMap;

    /**
     * 这个叫构造器注入，将列表service列表循环放到Map中
     *
     * @param deviceServices 参数是service列表
     */
    @Autowired
    public DeviceServiceFactory(List<DeviceService> deviceServices) {
        this.deviceServiceMap = deviceServices.stream()
                .collect(Collectors.toMap(
                        DeviceService::getDeviceType,
                        Function.identity()
                ));
    }

    public DeviceService getService(String deviceType) throws Exception {
        DeviceService service = deviceServiceMap.get(deviceType);
        if (service == null) {
            throw new Exception("Unsupported device type: " + deviceType);
        }
        return service;
    }
}
